<?php
declare(strict_types=1);

namespace app\admin\middleware;

use app\common\service\admin\AuthService;
use think\Request;

class CheckAdmin
{

    use \app\common\traits\JumpTrait;

    private array $configCache = [];

    public function handle(Request $request, \Closure $next): mixed
    {
        $adminConfig = config('admin');
        if (empty($adminConfig)) {
            return $next($request);
        }

        $adminId           = cmf_get_admin_id();
        $currentNode       = uncamelize($request->controller().'/'.$request->action());
        $currentController = parse_name($request->controller());

        // 登录验证
        if ($this->shouldCheckLogin($adminConfig, $currentController, $currentNode)) {
            if (empty($adminId)) {
                $this->removeLocalStorage();
                $this->error('请先登录', [], url('admin/login/index'));
            }

            //登录过期检查
            $currentUserInfo = cmf_get_current_admin_info();
            $expireTime      = null;
            if ($currentUserInfo && isset($currentUserInfo['expire_time'])) {
                $expireTime = $currentUserInfo['expire_time'];
            }

            if ($expireTime !== true && $expireTime !== null && time() > $expireTime) {
                cmf_admin_logout($adminId);
                $this->removeLocalStorage();
                $this->error('登录已过期，请重新登录', [], url('admin/login/index'));
            }
        }

        // 权限验证
        if ($this->shouldCheckAuth($adminConfig, $currentController, $currentNode)) {
            $checkNode = AuthService::instance()->check($currentNode, $adminId);
            if ( ! $checkNode) {
                $this->error('无访问权限！');
            }
        }

        return $next($request);
    }

    private function shouldCheckLogin(array $adminConfig, string $controller, string $node): bool
    {
        return ! in_array($controller, $adminConfig['no_login_controller'] ?? []) && ! in_array($node,
                $adminConfig['no_login_node'] ?? []);
    }

    private function shouldCheckAuth(array $adminConfig, string $controller, string $node): bool
    {
        return ! in_array($controller, $adminConfig['no_auth_controller'] ?? []) && ! in_array($node,
                $adminConfig['no_auth_node'] ?? []);
    }

    public function removeLocalStorage(): void
    {
        echo "<script>localStorage.removeItem('session-login-success-box');</script>";
    }
}
